import '../../core/base/base_view_model.dart';
import '../../core/http/api_response.dart';
import '../../core/http/http_client.dart';
import 'organization_model.dart';

class OrganizationListViewModel extends BaseViewModel {
  final _httpClient = HttpClient();
  List<OrganizationModel> organizations = [];
  List<OrganizationModel> filteredOrganizations = [];
  String searchKeyword = '';
  int currentPage = 1;
  int pageSize = 10;
  int total = 0;
  bool hasMore = true;

  Future<void> fetchOrganizations({int page = 1}) async {
    try {
      setBusy(true);
      final response = await _httpClient.get<PaginationData<OrganizationModel>>(
        '/organization/list',
        params: {
          'page': page,
          'page_size': pageSize,
        },
        fromJson: (json) => PaginationData.fromJson(json as Map<String, dynamic>, (item) => OrganizationModel.fromJson(item as Map<String, dynamic>),),
      );

      if (response.isSuccess) {
        final paginationData = response.data!;
        organizations = paginationData.list;
        total = paginationData.total;
        currentPage = page;
        _filterOrganizations();
        setState(organizations.isEmpty ? ViewState.empty : ViewState.idle);
      } else {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  Future<void> deleteOrganization(int id) async {
    try {
      setBusy(true);
      final response = await _httpClient.delete<void>('/organization/$id');

      if (response.isSuccess) {
        await fetchOrganizations(page: currentPage);
      } else {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  void setSearchKeyword(String keyword) {
    searchKeyword = keyword;
    _filterOrganizations();
    notifyListeners();
  }

  void _filterOrganizations() {
    if (searchKeyword.isEmpty) {
      filteredOrganizations = List.from(organizations);
    } else {
      filteredOrganizations = organizations
          .where((org) => org.name.toLowerCase().contains(searchKeyword.toLowerCase()) || org.contactPerson.toLowerCase().contains(searchKeyword.toLowerCase()))
          .toList();
    }
  }

  Future<void> createOrganization(Map<String, dynamic> data) async {
    try {
      setBusy(true);
      final response = await _httpClient.post<void>('/organization', data: data);

      if (response.isSuccess) {
        await fetchOrganizations(page: currentPage);
      } else {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  Future<void> updateOrganization(int id, Map<String, dynamic> data) async {
    try {
      setBusy(true);
      final response = await _httpClient.put<void>('/organization/$id', data: data);

      if (response.isSuccess) {
        await fetchOrganizations(page: currentPage);
      } else {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }
}
